package forum;

import forum.entities.Category;
import forum.entities.Post;
import forum.entities.Topic;
import forum.entities.User;
import forum.dao.factories.DAOAbstractFactory;
import forum.dao.factories.MySQLDAOFactory;

import java.math.BigInteger;
import java.util.List;

public class UserManager {

    private static DAOAbstractFactory factory = new MySQLDAOFactory();

    public static void setFactory(DAOAbstractFactory newFactory) {
        factory = newFactory;
    }

    public static void register(String email,String nickname,String password) {
        User user = factory.getUserDAO().create();
        user.setEmail(email);
        user.setNickName(nickname);
        user.setPassword(password);
        factory.getUserDAO().update(user);
    }

    public static User login(String email,String password) {
        User foundUser = factory.getUserDAO().findUserByEmail(email);
        if (foundUser == null) {
            throw new IllegalArgumentException("incorrect email");
        }
        if (!foundUser.getPassword().equals(password)) {
            throw new IllegalArgumentException("incorrect password");
        }
        return foundUser;
    }

    public static void createCategory(User user,Category currentCategory,String newCategoryName) {
        if (user == null) {
            throw new IllegalArgumentException("Unregistered users can't create forum categories");
        }

    }

    public static void createTopic(User user,Category currentCategory,String topicName) {
        if (user == null) {
            throw new IllegalArgumentException("Unregistered users can't create forum topics");
        }

    }

    public static void postMessage(User user,Topic topic,String postContains) {
        Post post = factory.getPostDAO().create();
        post.setAuthorId(user.getId());
        post.setTopicId(topic.getId());
        post.setPostContains(postContains);
        factory.getPostDAO().update(post);
    }

    public static Category getCategory(User user, BigInteger id) {
        return factory.getCategoryDAO().read(id);
    }

    public static void getCategoryContains(User user,Category currentCategory,
                                           List<Category> parentCategories, List<Topic> categoryTopics) {
        if (parentCategories == null) {
            // TODO Need to create an exception
            return;
        }
        parentCategories.addAll(factory.getCategoryDAO().findChildCategories(currentCategory.getId()));
    }

}
